package dbTest.connectionPool;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;

public class BeanFactory
{

	public static Stars getObj(String bean, ResultSet resultSet) throws Exception
	{
		HashMap<String, String> fields = new HashMap<String, String>();
		Object o = Class.forName(bean);
		Field[] ff = ((Class<?>) o).getDeclaredFields();
		Method mm[] = ((Class<?>) o).getDeclaredMethods();
		System.out.println("Fields:");
		for (Field f : ff)
		{
			Class<?> clazz = f.getType();
			fields.put(f.getName(), f.getType().toString());
			// System.out.println(f.getName() + "  " + f.getType());
			// System.out.println(clazz);
		}
		System.out.println("methods:");
		ResultSetMetaData rsmd = resultSet.getMetaData();

		int columnCount = rsmd.getColumnCount();

		// The column count starts from 1
		for (int i = 1; i < columnCount + 1; i++)
		{
			String name = rsmd.getColumnName(i);
			if (!fields.containsKey(name))
				throw new Exception("Field " + name + " of result set is not into Bean " + o.toString());
			String getmethod = "set" + name;

			Stars s = new Stars();
			String filedType =fields.get(name);
			Class type = getPrimitiveType(filedType);
			System.out.println(type.getClass());
			Method m = ((Class<?>) o).getMethod(getmethod, type);
			if (type.toString().equalsIgnoreCase("String"))
			{
				m.invoke(o, resultSet.getString(name));
			}
			if (type.toString().equalsIgnoreCase("int"))
			{
				m.invoke(o, resultSet.getInt(name));
			}
			if (type.toString().equalsIgnoreCase("long"))
			{
				m.invoke(o, resultSet.getLong(name));
			}
			System.out.println(name);
		}

		// Method m = o.getMethod (nome, int.class, int.class);

		return null;
	}

	public static Class getPrimitiveType(String name)
	{
	if (name.equals("byte")) return byte.class;
	if (name.equals("short")) return short.class;
	if (name.equals("int")) return int.class;
	if (name.equals("long")) return long.class;
	if (name.equals("char")) return char.class;
	if (name.equals("float")) return float.class;
	if (name.equals("double")) return double.class;
	if (name.equals("boolean")) return boolean.class;
	if (name.equals("void")) return void.class;

	throw new IllegalArgumentException();
	}
}
